package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.Settings;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.CommonLikeUser;
import com.tanhua.domain.vo.CommonLikeUserVO;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.SettingsVO;
import com.tanhua.domain.vo.UserInfoVO;
import com.tanhua.dubbo.api.*;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuyp
 * @date 2021/01/26
 */
@Slf4j
@Service
public class UserInfoService {
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private SettingsApi settingsApi;
    @Reference
    private BlackListApi blackListApi;
    @Reference
    private UserLikeApi userLikeApi;
    @Reference
    private FriendApi friendApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    public ResponseEntity findById(Long id) {
        //1. 查询id对应的用户信息
        UserInfo userInfo = userInfoApi.findById(id);
        log.info("查询用户详情，参数：{}，结果是：{}", id, userInfo);

        //2. 把UserInfo转换成一个vo对象。注意：vo对象必须和API文档要求的数据完全一致
        UserInfoVO vo = new UserInfoVO();
        //   这个工具拷贝时，只会拷贝同名、同类型的属性值
        BeanUtils.copyProperties(userInfo, vo);
        vo.setAge(String.valueOf(userInfo.getAge()));

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity updateUserInfo(UserInfo userInfo) {
        //1. 根据token找到当前用户
        User user = UserHolder.getUser();

        //2. 把user的id设置到UserInfo里
        userInfo.setId(user.getId());

        //3. 更新到数据库
        userInfoApi.update(userInfo);

        return ResponseEntity.ok(null);
    }

    /**
     * 查询当前用户的通用设置
     */
    public ResponseEntity findSettings() {
        //1. 获取当前用户
        User user = UserHolder.getUser();

        //2. 查询陌生人问题
        Question question = questionApi.findByUserId(user.getId());

        //3. 查询通知设置
        Settings settings = settingsApi.findByUserId(user.getId());

        //4. 转换成VO对象
        SettingsVO vo = new SettingsVO();
        //4.1 设置陌生人问题
        if (question != null) {
            vo.setStrangerQuestion(question.getTxt());
        }
        //4.2 设置手机号
        vo.setPhone(user.getMobile());
        //4.3 设置通知设置
        if (settings != null) {
            BeanUtils.copyProperties(settings, vo);
        }else{
            vo.setPinglunNotification(true);
            vo.setLikeNotification(true);
            vo.setGonggaoNotification(true);
        }

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findBlackList(int page, int pagesize) {
        //1. 获取当前用户
        User user = UserHolder.getUser();

        //2. 分页查询当前用户的黑名单列表
        IPage<UserInfo> iPage = blackListApi.findBlackList(page, pagesize, user.getId());

        //3. 把结果转换成VO对象
        PageResult<UserInfo> vo = new PageResult<>();
        vo.setPage(page);
        vo.setPagesize(pagesize);
        vo.setCounts((int)iPage.getTotal());
        vo.setPages((int)iPage.getPages());
        vo.setItems(iPage.getRecords());

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity removeBlackList(long blackUserId) {
        //1. 获取当前用户id
        Long userId = UserHolder.getUserId();

        //2. 调用api，移除黑名单
        blackListApi.delete(userId, blackUserId);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity saveQuestion(String content) {
        //1. 获取当前用户
        Long userId = UserHolder.getUserId();

        //2. 查询当前用户的陌生人问题
        Question question = questionApi.findByUserId(userId);

        //3. 设置陌生人问题
        if (question == null) {
            //需要新增保存陌生人问题
            question = new Question();
            question.setUserId(userId);
            question.setTxt(content);
            questionApi.save(question);
        }else{
            //需要修改陌生人问题
            question.setTxt(content);
            questionApi.update(question);
        }

        return ResponseEntity.ok(null);
    }

    public ResponseEntity saveSettings(Settings settings) {
        //1. 获取当前用户id
        Long userId = UserHolder.getUserId();

        //2. 查询当前用户的通知设置
        Settings userSettings = settingsApi.findByUserId(userId);

        //3. 设置通知的开关数据
        if (userSettings == null) {
            // 新增数据
            settings.setUserId(userId);
            settingsApi.save(settings);
        }else{
            //修改数据
            settings.setId(userSettings.getId());
            settingsApi.update(settings);
        }

        return ResponseEntity.ok(null);
    }

    public ResponseEntity queryLikeCount() {
        //1. 调用API，查询互相喜欢的数量
        long friendCount = userLikeApi.queryFriendCount(UserHolder.getUserId());

        //2. 调用API，查询喜欢的数量
        long likeCount = userLikeApi.queryLikeCount(UserHolder.getUserId());

        //3. 调用API，查询粉丝的数量
        long fansCount = userLikeApi.queryFansCount(UserHolder.getUserId());

        Map<String, Object> result = new HashMap<>();
        result.put("eachLoveCount", friendCount);
        result.put("loveCount", likeCount);
        result.put("fanCount", fansCount);
        return ResponseEntity.ok(result);
    }

    /**
     * 查询列表
     * @param type 查询的类型
     *             1 相互喜欢
     *             2 喜欢的
     *             3 粉丝
     *             4 访客
     * @param page 页码
     * @param pagesize 查询几条
     * @param nickname 昵称
     */
    public ResponseEntity queryLikeList(Integer type, int page, int pagesize, String nickname) {

        PageResult<CommonLikeUser> pageResult = null;
        if (type == 1) {
            //分页查询 当前用户相互喜欢的列表：查询tanhua_users好友表，Friend==>本质是需要好友的id，缘分值 CommonLikeUser
            pageResult = userLikeApi.findFriendList(page, pagesize, UserHolder.getUserId());
        } else if (type == 2) {
            //分页查询 当前用户喜欢的 列表：查询user_like单向喜欢表，UserLike==>本质是需要对方的id，缘分值 CommonLikeUser
            pageResult = userLikeApi.findLikeList(page, pagesize, UserHolder.getUserId());
        } else if (type == 3) {
            //分页查询 喜欢当前用户的 列表：查询user_like单向喜欢表，UserLike==>本质是需要对方的id，缘分值 CommonLikeUser
            pageResult = userLikeApi.findFansList(page, pagesize, UserHolder.getUserId());
        } else if (type == 4) {
            //分页查询  当前用户的访客列表：查询visitors访客表，Visitor==>本质是需要访客的id，缘分值 CommonLikeUser
            pageResult = userLikeApi.findVisitorList(page, pagesize, UserHolder.getUserId());
        }

        //转换成VO对象
        List<CommonLikeUser> userList = pageResult.getItems();
        List<CommonLikeUserVO> voList = new ArrayList<>();
        for (CommonLikeUser user : userList) {
            CommonLikeUserVO vo = new CommonLikeUserVO();

            //查询对方的用户详情
            UserInfo userInfo = userInfoApi.findById(user.getTargetUserId());
            BeanUtils.copyProperties(userInfo, vo);

            vo.setMatchRate(user.getScore().intValue());
            vo.setAlreadyLove(false);

            voList.add(vo);
        }

        //构造返回值
        PageResult<CommonLikeUserVO> voPageResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult, voPageResult);
        voPageResult.setItems(voList);
        return ResponseEntity.ok(voPageResult);
    }

    /**
     * 粉丝-喜欢。对某个粉丝点击了“喜欢”
     * @param targetId 粉丝id
     */
    public ResponseEntity likeFans(long targetId) {
        //1. 删除单向的喜欢 targetId喜欢当前用户
        userLikeApi.remove(targetId, UserHolder.getUserId());
        //2. 建立双向的好友关系
        friendApi.addFriend(targetId, UserHolder.getUserId());
        //3. 把好友关系注册到环信。注意：好友双方都必须已经在环信注册过，否则好友关系添加失败
        //huanXinTemplate.addContactUser(UserHolder.getUserId(), targetId);

        return ResponseEntity.ok(null);
    }
}
